#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>

#define SERVER_PORT 5432
#define MAX_LINE 256
#define MAX_PENDING 5

void* thr(int s)
{
    char buf[MAX_LINE];
    int len;
    while(fgets(buf,sizeof(buf),stdin)){
        buf[MAX_LINE-1]='\0';
        len =strlen(buf)+1;
        send(s,buf,len,0);
    }
}

int main()
{
    struct sockaddr_in sin;
    int s,new_s;
    char buf[MAX_LINE];
    int len;

    bzero((char*)&sin,sizeof(sin));
    sin.sin_family =AF_INET;
    sin.sin_addr.s_addr=INADDR_ANY;
    sin.sin_port =htons(SERVER_PORT);
    
    if((s =socket(PF_INET,SOCK_STREAM,0)) <0)
    {
        perror("simplex-talk:socket");
        exit(1);
    }

    if (bind(s,(struct sockaddr*)&sin,sizeof(sin))<0)
    {
        perror("simplex-talk:bind");
        close(s);
        exit(1);
    }

    listen(s,MAX_PENDING);

    pthread_t tid;

    while (1)
    {
        if((new_s=accept(s,(struct sockaddr*)&sin,&len))<0){
            perror("simplex-talk:accept");
            exit(1);
        }

        if (pthread_kill(tid,0)!=0)
        {
            pthread_create(&tid,NULL,thr,new_s);
        }
        
        while (len = recv(new_s,buf,sizeof(buf),0))
        {
            fputs(buf,stdout);
        }
        
        close(new_s);

        
    }
    return 0;
}